package com.boruan.shengtangfeng.admin.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.ISubjectDao;
import com.boruan.shengtangfeng.core.dao.IVideoCategoryDao;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.*;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dto.VideoCategoryDto;
import com.boruan.shengtangfeng.core.entity.Log.OperateType;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.vo.VideoCategoryVo;
import com.boruan.shengtangfeng.core.vo.VideoVo;
import com.boruan.shengtangfeng.core.vo.mapper.VideoCategoryVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@SuppressWarnings("all")
@RequestMapping("/admin/video")
@Api(value = "", tags = {"NO:7 视频相关接口"})
public class VideoApi {
    @Autowired
    private IVideoService videoService;
    @Autowired
    private IVideoCommentService videoCommentService;
    @Autowired
    private ILogService sysLogService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IUserService userservice;
    @Autowired
    private IVideoCategoryDao videoCategoryDao;
    @Autowired
    private ISubjectDao subjectDao;

    @GetMapping("/page")
    @ApiOperation(value = "NO:7-2 分页获取视频", notes = "")
    public GlobalReponse<PageQuery<VideoVo>> page(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
													@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
													Video video) {
        PageQuery<Video> pageQuery = new PageQuery<Video>();
        pageQuery.setPageNumber(pageIndex);
        pageQuery.setPageSize(pageSize);
        video.setIsDeleted(false);
        videoService.pageQuery(pageQuery, video);
        List<Video> list = pageQuery.getList();
        List<VideoVo> vos = VideoVoMapper.MAPPER.toVo(list);
        for (VideoVo vo : vos) {
            if (vo.getCategoryId()!=null){
                if (vo.getType()==1){
                    Subject subject = subjectDao.unique(vo.getCategoryId());
                    vo.setCategoryName(subject.getName());
                }else {
                    if (vo.getCategoryId()!=0){
                        VideoCategory category = videoCategoryDao.unique(vo.getCategoryId());
                        vo.setCategoryName(category.getName());
                    }
                }
            }
        }
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("addVideo")
    @ApiOperation(value = "NO:15-3 添加视频", notes = "")
    public GlobalReponse addVideo(@RequestBody Video dto) {

        UserSubject userSubject=JwtUtil.getCurrentJwtUser();
        dto.setPublisher(userSubject.getName());
        dto.setPublishId(userSubject.getId());
        dto.setPublisherIcon(userSubject.getHeadImage());
        if(StringUtils.isBlank(dto.getImage())) {
            dto.setImage(dto.getContent()+"?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
        }
        videoService.addVideo(dto, userSubject.getId());

        return GlobalReponse.success();
    }

    @GetMapping("updateVideo")
    @ApiOperation(value = "NO:15-3 审核视频", notes = "")
    public GlobalReponse updateVideo(@RequestParam Long id, @RequestParam Integer type) {

        videoService.updateVideo(id, type, JwtUtil.getCurrentJwtUser().getId());

        return GlobalReponse.success();
    }
    @PostMapping("deleteVideo")
    @ApiOperation(value = "NO:15-3 删除视频", notes = "")
    public GlobalReponse deleteVideo(@RequestParam Long[] ids) {
        UserSubject user=JwtUtil.getCurrentJwtUser();
        for (Long id : ids) {
            videoService.deleteVideo(id, user.getId());
        }
        return GlobalReponse.success();
    }
    @GetMapping(value = "/confirmVideo")
    @ApiOperation(value = "NO:23-5 审核视频", notes = "")
    public GlobalReponse confirmVideo(String id,Integer status,String remark) {
        for (String s : id.split(",")) {
            Long videoId = Long.valueOf(s).longValue();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            UserSubject userSubject=JwtUtil.getCurrentJwtUser();
            Video video=videoService.findById(videoId);
            video.setStatus(status);
            video.setRemark(remark);
            videoService.save(video);
//        0 未审核 1 已审核 2 审核失败
            //用户上传的审核通过给用户发通知
            if(video.getUploadType()==1) {
                if(status==1) {
                    noticeService.addNotice(2, 1, videoId, video.getPublishId(), "内容审核通知","您于"+dateFormat.format(video.getCreateTime())+"发表过的视频"+"《"+video.getTitle()+"》，审核通过。");
                }else if(status==2){
                    if (remark!=null && !remark.equals("")){
                        noticeService.addNotice(2, 1, videoId, video.getPublishId(), "内容审核通知","您于"+dateFormat.format(video.getCreateTime())+"发表过的视频"+"《"+video.getTitle()+"》，"+"因"+remark+"审核不通过。");
                    }else {
                        noticeService.addNotice(2, 1, videoId, video.getPublishId(), "内容审核通知","您于"+dateFormat.format(video.getCreateTime())+"发表过的视频"+"《"+video.getTitle()+"》，"+"因存在敏感信息审核不通过。");

                    }
                }
            }
            Log sysLog = new Log();
            sysLog.setObjectId(video.getId());
            sysLog.setContent("管理员审核视频信息："+status);
            sysLog.setOperateType(OperateType.UPDATE);
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLogService.save(sysLog);
        }
        return GlobalReponse.success();
    }


    @GetMapping("/deleteComment")
    public GlobalReponse deleteComment(Long id) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();

        videoCommentService.deleteComment(id, userSubject.getId());

        return GlobalReponse.success();
    }

    @GetMapping("/getCategory")
    @ApiOperation(value = "NO:7-6 获取视频分类", notes = "")
    public GlobalReponse getCategory() {
        List<VideoCategoryVo> list = videoService.getCategory(0);
        return GlobalReponse.success(list);
    }

    @GetMapping("/getAllCategory")
    @ApiOperation(value = "NO:7-6 获取全部视频分类", notes = "")
    public GlobalReponse getAllCategory() {
        List<VideoCategoryVo> list = videoService.getAllCategory();
        return GlobalReponse.success(list);
    }

//    @GetMapping("/listCategory")
//    @ApiOperation(value = "NO:7-7 获取所有视频分类", notes = "")
//    public GlobalReponse<List<VideoCategoryVo>> listCategory(VideoCategory videoCategory) {
//        List<VideoCategory> list = videoService.getCategoryList(videoCategory);
//        return GlobalReponse.success(VideoCategoryVoMapper.MAPPER.toVo(list));
//    }
    
    @GetMapping("pageCategory")
    @ApiOperation(value = "NO:7-7 获取视频分类", notes = "")
    public GlobalReponse<VideoCategoryVo> pageCategory(VideoCategoryDto videoCategoryDto,
                                                 @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageQuery<VideoCategory> pageData = new PageQuery<VideoCategory>();
        if (videoCategoryDto.getType()!=null && videoCategoryDto.getType()==1){
            PageQuery<Subject> page = subjectDao.createLambdaQuery().andEq(Subject::getIsDeleted, false).page(pageIndex, pageSize);
            ArrayList<VideoCategoryVo> categories = new ArrayList<>();
            for (Subject subject : page.getList()) {
                VideoCategoryVo vo = new VideoCategoryVo();
                vo.setId(subject.getId());
                vo.setName(subject.getName());
                categories.add(vo);
            }
            pageData.setList(categories);
            return GlobalReponse.success(pageData);
        }
        pageData.setPageNumber(pageIndex);
        pageData.setPageSize(pageSize);
        videoService.pageQueryCategory(pageData,videoCategoryDto);

        List<VideoCategoryVo> list = VideoCategoryVoMapper.MAPPER.toVo(pageData.getList());
        VideoCategoryVo all = new VideoCategoryVo();
        //all.setId(0l);
        //all.setName("全部");
        //list.add(0,all);
        pageData.setList(list);

        return GlobalReponse.success(pageData);
    }


    @CrossOrigin
    @PostMapping(value = "/saveVideoCategory")
    @ApiOperation(value = "NO:7-8 添加视频分类", notes = "")
    public GlobalReponse saveVideoCategory(@RequestBody VideoCategory videoCategory) {
        try {
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            Log sysLog = new Log();
            if (videoCategory.getId() == null) {
                // 添加
                videoCategory.setCreateBy(userSubject.getName());
                videoCategory.setCreateTime(new Date());
                videoCategory.setIsDeleted(false);
                videoService.saveCategory(videoCategory);
                //记录日志
                sysLog.setObjectId(videoCategory.getId());
                sysLog.setContent("管理员添加视频分类信息");
                sysLog.setOperateType(OperateType.ADD);
            } else {
                // 更新
                VideoCategory old = videoService.getCategory(videoCategory.getId());
                old.setName(videoCategory.getName());
                old.setSort(videoCategory.getSort());
                old.setIsDefault(videoCategory.getIsDefault());
                old.setUpdateBy(userSubject.getName());
                old.setUpdateTime(new Date());
                videoService.saveCategory(old);
                //记录日志
                sysLog.setObjectId(old.getId());
                sysLog.setContent("管理员修改视频分类信息");
                sysLog.setOperateType(OperateType.UPDATE);
            }
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("管理员编辑视频分类失败:{}", e);
            return GlobalReponse.fail();
        }
        
    }

    @GetMapping("deleteCategory")
    @ApiOperation(value = "NO:15-1 删除视频分类", notes = "")
    public GlobalReponse deleteCategory(String id) {
        for (String s : id.split(",")) {
            Long categoryId = Long.valueOf(s).longValue();
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            VideoCategory category = videoService.getCategory(categoryId);
            category.setIsDeleted(true);
            category.setUpdateBy(userSubject.getId().toString());
            category.setUpdateTime(new Date());
            try {
                videoService.saveCategory(category);
                Log sysLog = new Log();
                sysLog.setContent("试题管理删除视频分类信息");
                sysLog.setCreateTime(new Date());
                sysLog.setOperater(userSubject.getId());
                sysLog.setObjectId(userSubject.getId());
                sysLog.setLogType(Log.LogType.ADMIN);
                sysLog.setOperateType(OperateType.DELETE);
                sysLogService.save(sysLog);
            } catch (Exception e) {
                log.error("试题管理删除视频分类信息失败:{}", e.getMessage());
                //return GlobalReponse.fail();
            }
        }
        return GlobalReponse.success();
    }

    @PostMapping("/pageVideoGrade")
    @ApiOperation(value = "V3C查看讲一讲点评")
    public GlobalReponse<PageQuery<VideoGrade>> pageVideoGrade(@ApiParam(value = "页码")@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                                                                   @ApiParam(value = "每页数量")@RequestParam(value = "pageSize")Integer pageSize,
                                                                   @ApiParam(value = "用户ID")@RequestParam(value = "userId",required = false)Long userId,
                                                                   @ApiParam(value = "关键词")@RequestParam(value = "keywords",required = false)String keywords,
                                                                   @ApiParam(value = "状态")@RequestParam(value = "status",required = false)Integer status){
        PageQuery<VideoGrade> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageNo);
        pageQuery.setPageSize(pageSize);
        if(status!=null){
            pageQuery.setPara("status",status);
        }
        if(userId!=null){
            pageQuery.setPara("userId",userId);
        }
        if(com.boruan.shengtangfeng.core.utils.StringUtils.isNotBlank(keywords)){
            pageQuery.setPara("remark",keywords);
        }
        videoService.pageVideoGrade(pageQuery);
        List<VideoGrade> list = pageQuery.getList();
        for (VideoGrade v : list) {
            User user = userservice.findById(v.getUserId());
            Video video = videoService.findId(v.getVideoId());
            v.set("user",user);
            v.set("video",video);
        }
        pageQuery.setList(list);
        return GlobalReponse.success(pageQuery);
    }

    @GetMapping("/findVideo")
    @ApiOperation(value = "V3E根据视频Id查询视频")
    public GlobalReponse<Video> findVideo(@RequestParam(value = "videoId")Long videoId){
        Video video = videoService.findId(videoId);
        return GlobalReponse.success(video);
    }

    @GetMapping("/delVideoGrade")
    @ApiOperation(value = "删除点评")
    public GlobalReponse delVideoGrade(@RequestParam(value = "gradeId")@ApiParam(value = "点评ID")String gradeId){
        for (String s : gradeId.split(",")) {
            videoService.delGrade(Long.valueOf(s).longValue());
        }
        return GlobalReponse.success("删除成功");
    }
}
